<template>
    <section>
        <DetailsHeader title="我的机器" class="mb-24" :showBack="false" />

        <div class="page-content">
            <div class="search-content">
                <div>
                    <a-button type="primary" class="mr-8" :disabled="multipleUp" @click="handleUp()">上架</a-button>
                    <a-button type="primary" class="mr-8" :disabled="multipleDown" @click="handleDown()">下架</a-button>
                    <a-button type="link" @click="getToken">获取token添加机器</a-button>
                </div>
                <div>
                    <a-select ref="select" v-model:value="form.status" placeholder="全部上架状态" allowClear class="mr-8"
                        @change="getList">
                        <a-select-option value="2">已上架</a-select-option>
                        <a-select-option value="1">已下架</a-select-option>
                    </a-select>
                    <a-select ref="select" v-model:value="form.isOnline" placeholder="全部在线状态" allowClear class="mr-8"
                        @change="getList">
                        <a-select-option value="-1">下线</a-select-option>
                        <a-select-option value="1">在线</a-select-option>
                    </a-select>
                    <a-select ref="select" v-model:value="form.isOnSale" placeholder="全部租用状态" allowClear class="mr-8"
                        @change="getList">
                        <a-select-option value="1">未出租</a-select-option>
                        <a-select-option value="2">已出租</a-select-option>
                    </a-select>

                    <a-input-search v-model:value="form.machineId" placeholder="请输入机器ID"
                        style="width: 200px;margin-left: auto;" @search="getList" />
                </div>
            </div>

            <a-table :dataSource="tableList"
                :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" rowKey="machineId"
                :pagination="false">
                <a-table-column key="machineId" title="机器ID" data-index="machineId" />
                <a-table-column key="regionName" title="地区" data-index="regionName" />
                <a-table-column key="gpuName" title="GPU型号" data-index="gpuName" />
                <a-table-column key="phone" title="GPU租用/总数" data-index="phone">
                    <template #default="{ record }">
                        {{ record.gpuUsedNum }} / {{ record.gpuNum }}
                    </template>
                </a-table-column>
                <a-table-column key="price" title="单张价格(元)" data-index="price">
                    <template #default="{ record }">
                        <span v-for="item in record.skuList">
                            <div v-if="['daily', 'weekly', 'monthly', 'payg'].includes(item.skuName)">{{
                                selectDictLabel(freeTypeEnum, item.skuName) }}：{{ item.price }}</div>
                        </span>
                    </template>
                </a-table-column>
                <a-table-column key="rentEndTime" title="出租到期时间" data-index="rentEndTime" />
                <a-table-column key="payByVoucher" title="可用券" data-index="payByVoucher">
                    <template #default="{ record }">
                        {{ record.payByVoucher == 1 ? '可用' : '不可用' }}
                    </template>
                </a-table-column>

                <a-table-column key="phone" title="在线状态" data-index="phone">
                    <template #default="{ record }">
                        {{ record.isOnline == 1 ? '在线' : record.isOnline == -1 ? '离线' : '' }}
                    </template>
                </a-table-column>

                <a-table-column key="phone" title="上架状态" data-index="phone">
                    <template #default="{ record }">
                        {{ record.status == 1 ? '已上架' : record.status == 0 ? '未上架' : '' }}
                    </template>
                </a-table-column>
                <a-table-column key="gpuUsedNum" title="出租状态" data-index="gpuUsedNum">
                    <template #default="{ record }">
                        {{ record.status > 0 ? '已租用' : '未租用' }}
                    </template>
                </a-table-column>

                <a-table-column key="action" title="操作">
                    <template #default="{ record }">
                        <a-button type="link" @click="handleUp(record.machineId)" v-if="record.status == 0">上架</a-button>
                        <a-popconfirm title="确定要下架机器?" @confirm="handleDown(record.machineId)" @cancel="cancel">
                            <a-button type="link" v-if="record.status == 1">下架</a-button>
                        </a-popconfirm>
                        <a-dropdown>
                            <template #overlay>
                                <a-menu>
                                    <a-menu-item key="cache">
                                        <a-button type="link" @click="goEdit(record.machineId)"
                                            v-if="record.status == 0">编辑</a-button>
                                    </a-menu-item>
                                    <a-menu-item key="del">
                                        <a-popconfirm title="确定要删除机器?" @confirm="handleDel(record.machineId)"
                                            @cancel="cancel">
                                            <a-button type="link">删除</a-button>
                                        </a-popconfirm>
                                    </a-menu-item>
                                    <a-menu-item key="create">
                                        <a-button type="link" @click="goInstance(record.machineId)">创建实例</a-button>
                                    </a-menu-item>
                                    <a-menu-item key="del">
                                        <a-button type="link" @click="openOperationLog(record.machineId)">操作记录</a-button>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                            <a-button type="link" style="padding-left:0;">
                                更多
                                <DownOutlined />
                            </a-button>
                        </a-dropdown>
                    </template>
                </a-table-column>
            </a-table>

            <pagination v-show="total > 0" :total="total" v-model:page="form.pn" v-model:limit="form.ps"
                @pagination="getList" />
        </div>

        <!-- 操作记录 -->
        <a-modal v-model:visible="modalVisible" title="操作记录" @ok="handleOk">
            <a-table :dataSource="operationLogList" :pagination="false" rowKey="machineId">
                <a-table-column key="updated_at" title="操作时间" data-index="updated_at" />
                <a-table-column key="subject" title="操作内容" data-index="subject">
                    <template #default="{ record }">
                        {{ selectDictLabel(operationEnum, record.subject) }}
                    </template>
                </a-table-column>
                <a-table-column key="subject" title="操作人" data-index="operator_id">
                    <template #default="{ record }">
                        {{ formatOperator(record?.operator_id) }}
                    </template>
                </a-table-column>
            </a-table>

            <pagination v-show="operationLogTotal > 0" :total="operationLogTotal" v-model:page="operateForm.pn" v-model:limit="operateForm.ps"
                @pagination="getProviderActionlist" />
        </a-modal>

        <!-- 获取token -->
        <a-modal v-model:visible="tokenVisible" title="token" @ok="tokenVisible = false">
            <div>{{ token }}</div>
            <a-button @click="onCopy">复制</a-button>
        </a-modal>

    </section>
</template>

<script setup name="Machine">
import { ref, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { getMachineListApi, createMachineTokenApi, getMachineUpApi, getMachineDownApi, deleteMachineApi, getProviderActionlistApi } from 'api/modules/api.ownerMachine'
import DetailsHeader from '@/components/common/DetailsHeader.vue'
import clipboard3 from "vue-clipboard3";
import { XsyMessage } from '@/libs/util.toast'
import { selectDictLabel } from '@/libs/util.common'
const router = useRouter()

// 支付方式
const freeTypeEnum = [
    { label: '按天付费', value: 'daily' },
    { label: '按周付费', value: 'weekly' },
    { label: '按月付费', value: 'monthly' },
    { label: '按量付费', value: 'payg' }
]

// 机器操作
const operationEnum = [
    { label: '上架', value: 'up' },
    { label: '下架', value: 'down' },
    { label: '编辑', value: 'edit' },
]

const form = ref({
    pn: 1,
    ps: 10
})

// 获取列表
const tableList = ref([])
const total = ref(0)
const getList = () => {
    getMachineListApi(form.value).then(res => {
        res.code == 0 && (tableList.value = res.data.list)
        total.value = res.data.total
    })
};

getList()

// 操作记录
const operateForm = ref({
    pn: 1,
    ps: 10
})
const modalVisible = ref(false)
const operationLogList = ref([])
const operationLogTotal = ref(0)
const currentMachineId = ref('')
const getProviderActionlist = () => {
    const params = {
        ...operateForm.value,
        machineId: currentMachineId.value 
    }
    getProviderActionlistApi(params).then(res => {
        operationLogList.value = res.data.list || []
        operationLogTotal.value = res.data.total
    })
}

const openOperationLog = (machineId) => {
    modalVisible.value = true
    currentMachineId.value = machineId
    operateForm.value.pn = 1
    operateForm.value.ps = 10
    getProviderActionlist()
}

const handleOk = () => {
    modalVisible.value = false
}

// 获取token
const token = ref('')
const tokenVisible = ref(false)
const getToken = () => {
    createMachineTokenApi().then(res => {
        if (res.code == 0) {
            token.value = res.data.token
            tokenVisible.value = true
        }
    })
}

// 复制token功能
const { toClipboard } = clipboard3();
const onCopy = async () => {
    try {
        await toClipboard(token.value);
        XsyMessage.success('复制成功')
    } catch (e) {
        console.error(e);
    }
}

// 创建实例
const goInstance = (machineId) => {
    router.push({ path: '/owner/create-instance', query: { machineId } });
}

// 编辑机器
const goEdit = (machineId) => {
    router.push({ path: '/owner/machine-edit', query: { machineId } });
}

// 多选
const multipleUp = computed(() => {
    const upIndex = state.selectedRows.findIndex(item => {
        return item.status == 1
    })

    return !state.selectedRowKeys.length || upIndex > -1;
})

const multipleDown = computed(() => {
    const downIndex = state.selectedRows.findIndex(item => {
        return item.status == 0
    })

    return !state.selectedRowKeys.length || downIndex > -1;
})

const state = reactive({
    selectedRowKeys: [],
    selectedRows: []
});

const onSelectChange = (selectedRowKeys, selectedRows) => {
    state.selectedRowKeys = selectedRowKeys;
    state.selectedRows = selectedRows
};

// 删除机器
const handleDel = (machineId) => {
    deleteMachineApi({ machineIdList: [machineId] }).then(res => {
        if (res.code == 0) {
            XsyMessage.success('删除成功')
            state.selectedRowKeys = [];
            state.selectedRows = [];
            getList()
        }
    })
}

// 上架
const handleUp = (machineId) => {
    const params = {
        machineId: machineId ? [machineId] : state.selectedRowKeys
    }
    getMachineUpApi(params).then(res => {
        if (res.code == 0) {
            XsyMessage.success('上架成功')
            state.selectedRowKeys = [];
            state.selectedRows = [];
            getList()
        }
    })
}

// 下架
const handleDown = (machineId) => {
    const params = {
        machineId: machineId ? [machineId] : state.selectedRowKeys
    }
 
    getMachineDownApi(params).then(res => {
        if (res.code == 0) {
            XsyMessage.success('下架成功')
            state.selectedRowKeys = [];
            state.selectedRows = [];
            getList()
        }
    })
}

// 操作人
const formatOperator = (operator)=> {
    let str = ''
    if(operator == 'admin') {
        str = '管理员'
    }else if(operator == 'system') {
        str = '系统'
    }else {
        str = '本人'
    }

    return str
}

</script>

<style scoped lang="scss">
.page-content {
    background: #fff;
    padding: 24px;

    .search-content {
        display: flex;
        justify-content: space-between;
        margin-bottom: 24px;
    }
}
</style>
